package com.syqc.videos

import android.view.View
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import autodispose2.autoDispose
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import com.syqc.adapter.MediaAdapter
import com.syqc.comlib.base.LazyLoadSirFragment
import com.syqc.comlib.callback.EmptyCallback
import com.syqc.comlib.rx.filterFast
import com.syqc.comlib.utils.loadVideoImg
import com.syqc.comlib.utils.startActivityTo
import com.syqc.comlib.utils.toast
import com.syqc.entity.AlarmMedia
import com.syqc.maps.utils.LocationDialogActivity
import com.syqc.monitor.R
import com.syqc.monitor.databinding.FragmentAlarmPlayerBinding
import com.syqc.net.ServiceHelper


class AlarmPlayerFragment :
    LazyLoadSirFragment<FragmentAlarmPlayerBinding>(FragmentAlarmPlayerBinding::inflate) {
    private val mOrientationUtils: OrientationUtils by lazy {
        OrientationUtils(
            requireActivity(),
            binding.alarmPlayer
        )
    }
    private val mAdapter by lazy { MediaAdapter() }
    private var lat: Double = 0.0
    private var lng: Double = 0.0

    private var title = ""
    private var isLoad = false
    fun setTitle(title: String) {
        this.title = title
    }

    override fun initView(view: View) {
        mOrientationUtils.isEnable = false
        binding.alarmPlayer.titleTextView.isVisible = true
        binding.alarmPlayer.backButton.isVisible = false
        binding.alarmPlayer.isLockLand = true
        binding.alarmPlayer.isNeedLockFull = true

        binding.rvAlarm.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
        binding.rvAlarm.adapter = mAdapter

        binding.alarmPlayer.setVideoAllCallBack(object : SimpleVideoCallBack {
            override fun onPrepared(url: String?, vararg objects: Any?) {
                super.onPrepared(url, *objects)
                binding.ivAlarmMedia.isVisible = false
            }

            override fun onAutoComplete(url: String?, vararg objects: Any?) {
                super.onAutoComplete(url, *objects)
                if (isLoad) {
                    binding.ivAlarmMedia.isVisible = true
                    return
                }
            }

            override fun onComplete(url: String?, vararg objects: Any?) {
                super.onComplete(url, *objects)
                if (isLoad) {
                    binding.ivAlarmMedia.isVisible = true
                    return
                }
            }

            override fun onPlayError(url: String?, vararg objects: Any?) {
                super.onPlayError(url, *objects)
                if (isLoad) {
                    binding.ivAlarmMedia.isVisible = true
                    return
                }
                getNewUrl()
            }
        })
    }

    override fun initData() {

    }

    override fun initEvent() {
        binding.alarmPlayer.backButton.setOnClickListener {
            onBackPressed()
        }
        binding.alarmPlayer.fullscreenButton.setOnClickListener {
//            mOrientationUtils.resolveByClick()
            binding.alarmPlayer.startWindowFullscreen(requireContext(), false, true)
        }
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val entity = mAdapter.data[position]
            mAdapter.index = position
            mAdapter.notifyDataSetChanged()
            binding.ivAlarmMedia.loadVideoImg(requireContext(), entity.fullLink, 1000)
        }

        binding.tvAlarmAddress.filterFast {
            startActivityTo<LocationDialogActivity>(requireContext()){
                putExtra("lat", lat)
                putExtra("lng", lng)
            }
        }

    }

    fun setVideoData(
        data: MutableList<AlarmMedia.MediaInfo>,
        entity: AlarmMedia.MediaInfo
    ) {
        if (data.isEmpty()) {
            loadService.showCallback(EmptyCallback::class.java)
            return
        }
        loadService.showSuccess()
        setVideoDesc(entity)
        mAdapter.index = 0
        mAdapter.setList(data)
        lat = entity.glat.toDouble()
        lng = entity.glng.toDouble()
    }

    fun setTeamName(teamName: String) {
        binding.lrTvAlarmTeam.setRightText(teamName)
    }

    private var time: String = ""
    private var link: String = ""
    private fun setVideoDesc(entity: AlarmMedia.MediaInfo) {
        isLoad = false
        binding.lrTvAlarmTeam.setRightText(entity.teamName)
        binding.alarmPlayer.isVisible = true
        binding.alarmPlayer.release()
        time = entity.time
        link = entity.link
        binding.alarmPlayer.setUp(entity.fullLink, false, time)
        binding.lrTvAlarmTime.setRightText(entity.time)
        binding.lrTvAlarmSpeed.setRightText("${entity.speed} ${getString(R.string.unit_speed)}")

        binding.lrTvAlarmReason.setRightText(entity.reason)
        binding.tvAlarmAddress.text = entity.addr
        binding.ivAlarmMedia.loadVideoImg(requireContext(), entity.fullLink, 1000)
    }

    fun onBackPressed(): Boolean {
        mOrientationUtils.backToProtVideo()
        //先返回正常状态
        return GSYVideoManager.backFromWindowFull(activity);
    }


    override fun onPause() {
        super.onPause()
        binding.alarmPlayer.onVideoPause()
        GSYVideoManager.onPause();
    }

    override fun onResume() {
        super.onResume()
        binding.alarmPlayer.onVideoResume()
        GSYVideoManager.onResume();
    }

    override fun onDestroy() {
        binding.alarmPlayer.setVideoAllCallBack(null)
        super.onDestroy()
        mOrientationUtils.releaseListener()
        GSYVideoManager.releaseAllVideos();
    }


    fun getNewUrl() {
        ServiceHelper.getRepository().covertAlarmMedia(link).autoDispose(scopeProvider)
            .subscribe({
                binding.alarmPlayer.setUp(it.result.toString(), false, time)
                binding.alarmPlayer.startPlayLogic()
                isLoad = true
            }, {
                isLoad = true
                (it.message ?: getString(R.string.desc_no_about_data)).toast(requireContext())
            })
    }
}